<template>
  <div class="app-container bg">

    <el-row :gutter="20">
      <el-col :span="16">
        <div class="themm-black themm-bg">
          <div class="step-text">
            step1:对话生成
          </div>
          <el-form :model="taskDigitalPerson" ref="taskDigitalPerson" size="small" :rules="rules" :hide-required-asterisk="true" :inline="true" label-width="110px">
            <el-row>
              <el-col>
                <el-form-item label="视频主题：" prop="chatContent">
                  <el-input v-model="taskDigitalPerson.chatContent" placeholder="请输入视频主题" clearable style="width:600px"
                    @keyup.enter.native="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="受众：" prop="audienceId">
                  <el-select v-model="taskDigitalPerson.audienceId" placeholder="请选择受众" clearable style="width: 100%">
                    <el-option v-for="dict in audienceList" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="策略或要素" prop="strategyId">
                  <el-select v-model="taskDigitalPerson.strategyId" placeholder="请选择策略" @change="changeStrategy" style="width: 100%" :style="{opacity: taskDigitalPerson.strategyId ? 1 : .3}">
                    <el-option v-for="dict in strategyList" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="或" prop="elementIds" hide-required-asterisk label-width="30px">
                  <el-select v-model="taskDigitalPerson.elementIds" collapse-tags multiple placeholder="请选择要素" @change="changeElement" style="width: 100%" :style="{opacity: taskDigitalPerson.elementIds.length>0 ? 1 : .3}">
                    <el-option v-for="dict in factorsList" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="性格1：" prop="character1">
                  <el-select v-model="taskDigitalPerson.character1" placeholder="请选择性格1" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.character" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="性格2：" prop="character2">
                  <el-select v-model="taskDigitalPerson.character2" placeholder="请选择性格2" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.character" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="语言：" prop="language">
                  <el-select v-model="taskDigitalPerson.language" placeholder="请选择语言" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.language" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="create-template themm-bg themm-black">
            <div class="step-text" style="padding: 20px 0;">
              step2:选择模版
            </div>
            <div class="template-text ">
              <el-input v-model="taskDigitalPerson.title" placeholder="请输入标题" clearable style="width:100%"
                @keyup.enter.native="handleQuery" />
            </div>
            <div class="template-card">
              <div class="template-video">
                <div v-for="(item, index) in digitalHuman">
                  <!-- <vue-d-player v-if="taskDigitalPerson.templateId == item.id" :key="item.id"
                    :options="{ video: { url: item.url, pic: item.url } }"></vue-d-player> -->
                    <video v-if="taskDigitalPerson.templateId == item.id" :controls="true" controlslist="noplaybackrate nodownload" :key="item.id" disablePictureInPicture
                      oncontextmenu="return false" name="media" class="frame-img" style="width: 100%;height: 100%;">
                      <source :src="item.url" type="video/mp4">
                    </video>
                </div>
              </div>
              <div class="template-list">
                <div class="template-item" v-for="(item, index) in digitalHuman" :key="item.id">
                  <div class="template-img">
                    <video style="width: 100%;height: 100%;" :src="item.url"></video>
                  </div>
                  <div class="template-title">
                    <el-radio v-model="templateObj" @change="changeTemplate" :label="item.id">{{ item.description }}</el-radio>
                  </div>
                </div>
              </div>
            </div>
          </div>
      </el-col>
      <el-col :span="8">
        <div class="create-template themm-bg themm-black" style="padding-bottom: 38px;">
          <div style="text-align: right;margin-right: 20px;margin-bottom: 20px;padding-top: 15px;">
            <el-button type="primary" class="primary-btn" size="mini" @click="createVideoText">生成文案</el-button>
            <el-button type="primary" class="primary-btn" size="mini" @click="createVoice">生成语音</el-button>
            <el-button type="primary" class="primary-btn" size="mini" @click="downVoice">导出语音</el-button>
          </div>
          <div class="create-video-text themm-black">
            <el-input :rows="32" v-model="taskDigitalPerson.dialogue" type="textarea" />
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="volume-footer">
          <el-button type="primary" class="reset-btn" size="mini" @click="resetVideoText">重置内容</el-button>
          <el-button type="primary" class="primary-btn" size="mini" @click="createVideo">生成视频</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getInitTask, getFileTemplate, getTask } from "@/api/content/task";
import { getAudienceAllList } from "@/api/library/audience";//受众接口表
import { getStrategyList } from "@/api/library/strategy";//策略接口表
import { getFactorsList } from "@/api/library/factors";//心里要素接口表
import { createDigitalPersonGenerationText, replaceDigitalPerson, digitalPersonGenerationAudio } from "@/api/content/algorithm";//算法接口表
export default {
  name: "Task",
  dicts: ['character', 'language'],
  data() {
    var checkStrategt = (rule, value, callback) => {
      console.log(value,this.taskDigitalPerson.elementIds,'asdasd')
      setTimeout(() => {
        if (!value && !this.taskDigitalPerson.elementIds) {
          callback(new Error('请选择策略'));
        } else {
          // this.$refs.form.taskDigitalPerson("elementIds");
          callback();
        }
      }, 500);
    };
    var checkElement = (rule, value, callback) => {
      setTimeout(() => {
        if (!value  && !this.taskDigitalPerson.strategyId) {
          callback(new Error('请选择心理要素'));
        } else {
          // this.$refs.form.taskDigitalPerson("strategyId");
          callback();
        }
      }, 500);
    };
    return {
      loading: true,
      rules: {
        chatContent: [
          { required: true, message: "请输入视频主题", trigger: "blur" }
        ],
        audienceId: [
          { required: true, message: "请选择受众", trigger: "blur" }
        ],
        strategyId: [
          { validator: checkStrategt, trigger: 'blur' }
        ],
        elementIds: [
          { validator: checkElement, trigger: 'blur' },
        ],
        character1: [
          { required: true, message: "请选择性格1", trigger: "blur" }
        ],
        character2: [
          { required: true, message: "请选择性格2", trigger: "blur" }
        ],
        language: [
          { required: true, message: "请选择语言", trigger: "blur" }
        ],
      },
      audienceList: [],
      strategyList: [],
      factorsList: [],
      digitalHuman: [],
      taskDigitalPerson: {
        elementIds:[]
      },
      templateObj: ''
    };
  },
  watch: {

  },
  mounted() {
    this.getAudioTemplate()
    this.getAudienceList()
    this.getStrategyList()
    this.getFactorsList()
    if (this.$route.query.id) {
      this.getTask(this.$route.query.id)
    } else {
      this.getInitTask()
    }
    
  },
  methods: {
    // 创建任务工作目录
    async getInitTask() {
      const res = await getInitTask({ type: 'DIGITAL_PERSON' })
      console.log(res, '工作目录')
      this.taskDigitalPerson = res.data.taskDigitalPerson
      this.workDir = res.data.workDir
      this.$set(this.taskDigitalPerson,'elementIds',[])
      // 默认数据
      this.$set(this.taskDigitalPerson,'audienceId',this.audienceList[0].id)
      this.$set(this.taskDigitalPerson,'strategyId',this.strategyList[0].id)
      this.$set(this.taskDigitalPerson,'language',this.dict.type.language[0].value)
    },
    // 获取任务详情
    async getTask(id) {
      const res = await getTask(id)
      console.log(res);
      this.taskDigitalPerson = res.data.taskDigitalPerson
      this.templateObj = res.data.taskDigitalPerson.templateId
      this.taskDigitalPerson.audienceId = Number(this.taskDigitalPerson.audienceId)
      // this.taskDigitalPerson.elementIds = this.taskDigitalPerson.elementId.split(',');
      this.$set(this.taskDigitalPerson, 'elementIds', this.taskDigitalPerson.elementId?this.taskDigitalPerson.elementId.split(','):[])
    },
    // 获取数字人模板
    async getAudioTemplate() {
      const { data: res } = await getFileTemplate('digital_human');
      console.log(res);
      this.digitalHuman = res
    },
    // 获取受众列表
    async getAudienceList() {
      const { data: res } = await getAudienceAllList(this.query);
      this.audienceList = res;
    },
    // 获取策略列表
    async getStrategyList() {
      const { data: res } = await getStrategyList(this.query);
      this.strategyList = res;
    },
    // 获取心里要素列表
    async getFactorsList() {
      const { data: res } = await getFactorsList(this.query);
      console.log(res);
      this.factorsList = res;
    },
    // 选择模版
    changeTemplate(e) {
      console.log(e);
      this.taskDigitalPerson.templateId = e
      // this.taskDigitalPerson.videoPath = e.url
    },
    // 生成数字人对话
     createVideoText() {
      this.taskDigitalPerson.elementId = this.taskDigitalPerson.elementIds?this.taskDigitalPerson.elementIds.join(','):''
      this.$refs["taskDigitalPerson"].validate(valid => {
        if (valid) {
          this.openLoading();
          createDigitalPersonGenerationText(this.taskDigitalPerson).then(res=>{
            console.log(res);
            this.taskDigitalPerson.dialogue = res.data.dialogue;
            this.$modal.closeLoading();
          }).catch(err=>{
            this.$modal.closeLoading();
          })
          
        }
      });
    },
    // 生成语音
    createVoice() {
      const params = {
        ...this.taskDigitalPerson,
      }
     
      this.$refs["taskDigitalPerson"].validate(valid => {
        if (valid) {
          console.log(params, '语音生成入参')
          this.openLoading();
          digitalPersonGenerationAudio(params).then(res => {
            console.log(res);
            this.taskDigitalPerson.audioPath = res.data.audioPath;
            this.$modal.closeLoading();
          }).catch(err=>{
            this.$modal.closeLoading();
          })
          
        }
      });
      

    },
    // 生成数字人视频
    createVideo() {
      const params = {
        ...this.taskDigitalPerson,
      }
      this.$refs["taskDigitalPerson"].validate(valid => {
        if (valid) {
          if(params.title=='' || params.title==null || params.title == undefined ){
            this.$message.error('请输入标题')
            return
          }
          if(params.templateId=='' || params.templateId==null || params.templateId == undefined){
            this.$message.error('请选择模版')
            return
          }
          this.openLoading();
          replaceDigitalPerson(params).then(res=>{
            console.log(res)
            this.$modal.msgSuccess('生成成功');
            this.$modal.closeLoading();
          }).catch(err=>{
            this.$modal.closeLoading();
          })
         
        }
      });
    },
    // 重置
    resetVideoText() {
      this.taskDigitalPerson = {
        chatContent: undefined,
        audienceId: undefined,
        strategyId: undefined,
        elementIds: [],
        character1: undefined,
        character2: undefined,
        language: undefined,
        title: undefined,
        templateId: undefined,
        videoPath: undefined,
      };
      this.templateObj = ""
      this.resetForm("taskDigitalPerson");
    },
    // 导出
    downVoice() {

    },
    openLoading() {
      this.$modal.loading("正在生成，请稍候！");
    },
     // 选择策略
     changeStrategy(){
      this.$set(this.taskDigitalPerson,'elementIds',[])
    },
    // 选择要素
    changeElement(){
      this.taskDigitalPerson.strategyId = null
    },
  }
};
</script>
<style lang="scss" scoped>
.step-text {
  color: #fff;
  font-size: 14px;
  padding: 20px;
}

.voice-select {
  padding: 0 65px;
  position: relative;
}

.volume-footer {
  display: flex;
  justify-content: flex-end;
  background: rgba(255, 255, 255, .1);
  margin-top: 20px;
  padding: 20px;
  margin-left: -30px;
  margin-right: -30px;
}

.app-container {
  padding-bottom: 0;
}

.bg {
  background-image: url("../../../assets/images/content_bg.png");
  background-size: 25%;
  background-repeat: no-repeat;
  background-position: top right;
}

.template-card {
  display: flex;
  margin-top: 20px;

  .template-video {
    flex: 1;
    height: 400px;
    background: rgba(255, 255, 255, .2);
    overflow: hidden;
  }

  .template-list {
    width: 400px;
    max-height: 400px;
    overflow-y: scroll;
    display: flex;
    flex-wrap: wrap;
    background: rgba(255, 255, 255, .2);
    margin-left: 20px;
    padding: 0 6px;

    .template-item {
      width: 50%;
      padding: 0 6px 0;

      .template-img {
        height: 130px;
        border-radius: 4px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .template-title {
        color: #fff;
        margin-bottom: 10px;
        font-size: 12px;

        .ellipsis {
          width: 150px;
        }
      }
    }
  }
}

.create-template {
  padding-top: 0;
  padding: 0 20px 20px;
}
::v-deep {
  .themm-black .el-textarea__inner {
    border: none !important;
    color: #fff;
  }

  .el-checkbox {
    color: #fff;
    display: flex;
    align-items: center;
  }

  .el-checkbox__label {
    padding-left: 5px;
  }

  .el-radio__label {
    color: #fff;
  }
}
</style>